package com.briup.sms_plus.common.util;

import com.briup.sms_plus.common.model.Request;
import com.briup.sms_plus.common.model.Response;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class InternetUtil {

    // 发送请求
    public static Response<?> sendRequest(Socket socket, Request<?> request) throws Exception {
        // 获取对象输出流对象，将请求对象写出到服务器中
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(request);
        oos.flush();
        socket.shutdownOutput();

        // 接收来自于服务器的响应
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        Object o = ois.readObject();
        if (o instanceof Response<?> r) {
            return r;
        }
        throw new RuntimeException("出现异常");
    }

    // 用于服务器接收请求，和客户端接收响应
    public static <T> T receive(Socket client, Class<T> tClass) throws Exception {
        // 创建对象输入流对象，用于接收来自于客户端的请求
        ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
        Object o = ois.readObject();
        // 转换类型
        if (tClass.isInstance(o)) {
            return tClass.cast(o);
        }
        throw new RuntimeException("出现异常");
    }

    public static void sendResponse(Socket client, Response<?> response) throws IOException {
        // 获取对象输出流对象，将响应对象写出到客户端中
        ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
        oos.writeObject(response);
        oos.flush();
        client.shutdownOutput();
    }
}
